<template>
  <div>
    <div v-show="goodsListShow">
      <div class="goods-table">
        <el-table
          stripe
          border
          :data="goods"
          :default-sort = "{prop: 'createDate', order: 'descending'}">
          <!--:data="goods.slice((currentPage-1)*pagesize,currentPage*pagesize)"-->
          <el-table-column prop="goodsSn" label="商品货号" width="180" sortable></el-table-column>
          <el-table-column prop="goodsName" label="商品名称" width="180"></el-table-column>
          <el-table-column prop="createDate" label="添加时间" width="160" sortable></el-table-column>
          <el-table-column prop="keywords" label="商品关键字" width="100"></el-table-column>
          <el-table-column prop="goodsUnit" label="单位" width="50"></el-table-column>
          <el-table-column prop="shopPrice" label="销售价" width="80"></el-table-column>
          <el-table-column prop="costPrice" label="成本价" width="80"></el-table-column>
          <el-table-column prop="goodsWeight" label="重量（kg）" width="100"></el-table-column>
          <el-table-column prop="goodsBrief" label="简短描述" width="120"></el-table-column>
          <el-table-column
            prop="reviewStatus"
            label="状态"
            width="100"
            :filters="reviewStatusFilters"
            :filter-method="reviewStatusfilterTag">
              <template slot-scope="scope">
                <el-tag :type="reviewStatusType(scope.row.reviewStatus)">
                {{reviewStatusShowText(scope.row.reviewStatus)}}
                </el-tag>
              </template>
          </el-table-column>
          <el-table-column fixed="right" width="400" label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-upload"
                :disabled="buttonDisabled(scope.row.reviewStatus, 1)"
                @click="handleSubmit(scope.$index, scope.row)">提交</el-button>
              <el-button
                size="mini"
                icon="el-icon-edit"
                :disabled="buttonDisabled(scope.row.reviewStatus, 2)"
                @click="handleEdit(scope.$index, scope.row)">详情/编辑</el-button>
              <el-button
                size="mini"
                icon="el-icon-tickets"
                :disabled="buttonDisabled(scope.row.reviewStatus, 3)"
                @click="stockEdit(scope.$index, scope.row)">库存</el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                :disabled="buttonDisabled(scope.row.reviewStatus, 4)"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 35, 50]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="goodsTotal">
        </el-pagination>
      </div>
    </div>

    <div v-show="goodsEditShow">
      <!-- 商品编辑---开始 -->
      <!-- 分类选择---开始 -->
      <el-form :model="goodInfo" :rules="addInfoRules" ref="goodInfo" label-width="110px">
        <fieldset style="border: none;padding: 0;border-top: 1px solid #eee;">
          <legend>
            <a name="hr">分类选择</a>
          </legend>
        </fieldset>
        <el-row style="margin-bottom: 0px; margin-top: 20px;">
          <el-col :span="6">
            <el-form-item label="选择分类">
              <el-select value-key="id" :disabled="disabledGoods" v-model="categoryTopId" filterable clearable placeholder="请选择" @change="changeTopCategory">
                <el-option
                  v-for="item in categorys"
                  :key="item.id"
                  :label="item.catName"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级分类">
              <el-select value-key="id" :disabled="categorySecondDisabled" v-model="categorySecondId" filterable placeholder="请选择" @change="changeSecondCategory">
                <el-option
                  v-for="item in categorySeconds"
                  :key="item.id"
                  :label="item.catName"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="三级分类">
              <el-select value-key="id" :disabled="categoryThirdDisabled" v-model="categoryThirdId" filterable placeholder="请选择" @change="changeThirdCategory">
                <el-option
                  v-for="item in categoryThirds"
                  :key="item.id"
                  :label="item.catName"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 分类选择---结束 -->
        <!-- 基本信息---开始 -->
        <fieldset style="border: none;padding: 0;border-top: 1px solid #eee;">
          <legend>
            <a name="hr">基本信息</a>
          </legend>
        </fieldset>
        <el-row style="margin-top: 20px;">
        <el-col :span="6">
          <el-form-item label="商品货号：" prop="goodsSn">
            <el-input v-model="goodInfo.goodsSn" placeholder="请输入商品货号" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品名称：" prop="goodsName">
            <el-input v-model="goodInfo.goodsName" placeholder="请输入商品名称" :disabled="disabledGoods"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item  label="单位：" prop="goodsUnit">
            <el-input v-model="goodInfo.goodsUnit" placeholder="请输入商品单位" :disabled="disabledGoods"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item  label="关键字：" prop="keywords">
            <el-input v-model="goodInfo.keywords" placeholder="请输入商品关键字" :disabled="disabledGoods"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item  label="重量（kg）：" prop="goodsWeight">
            <el-input v-model="goodInfo.goodsWeight" placeholder="请输入商品重量" :disabled="disabledGoods"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item  label="销售价：" prop="shopPrice">
            <el-input v-model="goodInfo.shopPrice" placeholder="请输入销售价" :disabled="disabledGoods"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item  label="成本价：" prop="costPrice">
            <el-input v-model="goodInfo.costPrice" placeholder="请输入成本价" :disabled="disabledGoods"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item  label="市场价：" prop="marketPrice">
            <el-input v-model="goodInfo.marketPrice" placeholder="请输入市场价" :disabled="disabledGoods"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item  label="简短描述：" prop="goodsBrief">
            <el-input v-model="goodInfo.goodsBrief" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入商品简短描述(不超过50字)" :disabled="disabledGoods"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item  label="详细描述：" prop="goodsDesc">
            <el-input v-model="goodInfo.goodsDesc" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入商品详细描述（不超过100字）" :disabled="disabledGoods"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item  label="备注：" prop="sellerNote">
            <el-input v-model="goodInfo.sellerNote" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="商家备注（仅商家可见；不超过100字）" :disabled="disabledGoods"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="20">
          <el-form-item label="详情轮播图：" :required="true">
            <el-upload
              :disabled="disabledGoods"
              class="upload-demo"
              ref="uploadImgList"
              action="http://localhost:8888/shopGoods/data/uploadFile"
              :headers="uploadHeaders"
              list-type="picture-card"
              :file-list="imgList"
              :limit="10"
              :on-exceed="exceedImgList"
              :before-upload="beforeUploadImgList"
              :on-success="successImgList"
              :on-remove="removeImgList">
              <i class="el-icon-plus"></i>
              <div class="el-upload__tip" slot="tip">详情页轮播图（最多不超过10张图）</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 0px">
        <el-col :span="20">
          <el-form-item label="展示图：" :required="true">
            <el-upload
              :disabled="disabledGoods"
              class="upload-demo"
              ref="uploadImgThumb"
              action="http://localhost:8888/shopGoods/data/uploadFile"
              :headers="uploadHeaders"
              list-type="picture-card"
              :file-list="imgThumb"
              :limit="15"
              :on-exceed="exceedImgThumb"
              :before-upload="beforeUploadImgThumb"
              :on-success="successImgThumb"
              :on-remove="removeImgThumb">
              <i class="el-icon-plus"></i>
              <div class="el-upload__tip" slot="tip">商品列表展示图（最多不超过15张图）</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      </el-form>
      <!-- 基本信息---结束 -->
      <!-- 分类属性---开始 -->
      <fieldset style="border: none;padding: 0;border-top: 1px solid #eee; margin-bottom: 20px">
        <legend>
          <a name="hr">分类属性</a>
        </legend>
      </fieldset>
      <el-form :model="attributeForm" ref="attributeForm" label-width="110px">
        <el-row
          v-for="(attribute, indexTop) in attributeForm.attributes"
          :key="indexTop">
          <el-col :span="8">
            <el-form :model="attribute" ref="attribute" label-width="110px">
              <el-form-item
                v-for="(goodsAttr, indexAttr) in attribute.goodsAttrs"
                :label="goodsAttr.attrName+'-'+(indexAttr)+'：'"
                :key="goodsAttr.attrSort"
                :prop="'goodsAttrs.'+indexAttr+'.attrValue'"
                :rules="{ required: true, message: '请输入“'+goodsAttr.attrName+'-'+indexAttr+'”的属性值', trigger: 'blur' }">
                <el-row>
                  <el-col :span="18">
                    <el-input v-model="goodsAttr.attrValue" :disabled="disabledGoods"></el-input>
                  </el-col>
                  <el-col :span="4" :offset="2">
                    <el-button @click.prevent="removeGoodsAttr(goodsAttr, attribute)" icon="el-icon-delete" :disabled="disabledGoods"></el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="4" :offset="1">
            <el-button @click="addGoodsAttr(attribute, indexTop)" icon="el-icon-plus" :disabled="disabledGoods"></el-button>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="blackGoodsList"><i class="el-icon-back el-icon--left"></i>返回</el-button>
          <el-button type="primary" @click="editBoolean" v-show="editBooleanShow"><i class="el-icon-edit el-icon--left"></i>编辑</el-button>
          <!--<el-button type="warning" @click="rejectBoolean"><i class="el-icon-edit el-icon&#45;&#45;left"></i>驳回</el-button>-->
          <el-button type="primary" @click="resetAllInfo" v-show="resetDisable"><i class="el-icon-refresh el-icon--left"></i>重置</el-button>
          <el-button type="primary" @click="submitForm('goodInfo')" v-show="resetDisable"><i class="el-icon-upload2 el-icon--left"></i>保存</el-button>
        </el-form-item>
      </el-form>
      </el-form>
      <!-- 分类属性---结束 -->
      <!-- 商品编辑---结束 -->
    </div>
    <div v-show="productInfoShow">
      <!-- 商品加库存---开始 -->
      <el-form :model="productInfos" ref="productInfos" label-width="110px">
        <fieldset style="border: none;padding: 0;border-top: 1px solid #eee; margin-bottom: 20px;">
          <legend>
            <a name="hr">{{productInfos.productsName}}</a>
          </legend>
        </fieldset>
        <el-row>
          <el-col :span="24">
            <el-form-item
              v-for="(productInfo, index) in productInfos.products"
              :label="productInfo.productName+'：'"
              :key="productInfo.productSort">
              <el-row>
                <el-col :span="4">
                  <el-form-item
                    label="库存："
                    :prop="'products.'+index+'.productNumber'"
                    :rules="{ required: true, validator: productNumberRule, trigger: 'blur' }">
                    <el-input v-model="productInfo.productNumber" @change="productNumberChange"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item
                    label="警报库存："
                    :prop="'products.'+index+'.productWarnNumber'"
                    :rules="{ required: true, validator: productWarnNumberRule, trigger: 'blur' }">
                    <el-input v-model="productInfo.productWarnNumber"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item
                    label="溢价："
                    :prop="'products.'+index+'.productPrice'"
                    :rules="{ required: true, validator: productPriceRule, trigger: 'blur' }">
                    <el-input v-model="productInfo.productPrice"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-row>
                <el-col :span="4">
                  <el-form-item label="总库存">
                    <el-input v-model="productAllNumber" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="blackGoodsList"><i class="el-icon-back el-icon--left"></i>返回</el-button>
          <el-button type="primary" @click="submitProducts('productInfos')"><i class="el-icon-upload2 el-icon--left"></i>保存</el-button>
        </el-form-item>
      </el-form>
      <!-- 商品加库存---结束 -->
    </div>
  </div>
</template>
<script>

import forSaleApi from '@/api/backstage/forSale'
import { getToken } from '@/utils/auth'

export default {
  name: 'forSale_Review',
  data() {
    const validateGoodsName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入商品名称'));
      }
      callback(this.valueLengthRule(value, '商品名称', 100));
    }
    const validateGoodsUnit = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入商品单位'));
      }
      callback(this.valueLengthRule(value, '商品单位', 3));
    }
    const validateKeywords = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入商品关键字'));
      }
      callback(this.valueLengthRule(value, '商品关键字', 30));
    }
    const validateGoodsWeight = (rule, value, callback) => {
      if (value === ''){
        callback(new Error('请输入商品重量'));
      }
      let weightRegex = /^([1-9]\d{0,6}|0)([.]?|(\.\d{1,3})?)$/
      if (!weightRegex.test(value)){
        callback(new Error('商品重量范围在0.000~9999999.999（最多保留3位小数）'));
      }
      callback();
    }
    const validateShopPrice = (rule, value, callback) => {
      if (value === ''){
        callback(new Error('请输入商品销售价格'));
      }
      let shopPriceRegex = /^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$/
      if (!shopPriceRegex.test(value)){
        callback(new Error('商品销售价格范围在0.00~9999999.99（最多保留2位小数）'));
      }
      callback();
    }
    const validateCostPrice = (rule, value, callback) => {
      if (value === ''){
        callback(new Error('请输入商品成本价格'));
      }
      let shopPriceRegex = /^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$/
      if (!shopPriceRegex.test(value)){
        callback(new Error('商品销售价格范围在0.00~9999999.99（最多保留2位小数）'));
      }
      callback();
    }
    const validateMarketPrice = (rule, value, callback) => {
      if (value === ''){
        callback();
      } else {
        let marketPriceRegex = /^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$/
        if (!marketPriceRegex.test(value)){
          callback(new Error('商品销售价格范围在0.00~9999999.99（最多保留2位小数）'));
        }
      }
      callback();
    }
    const validateGoodsBrief = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入简短描述'));
      }
      callback(this.valueLengthRule(value, '简短描述', 50));
    }
    const validateGoodsDesc = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入详细描述'));
      }
      callback(this.valueLengthRule(value, '详细描述', 50));
    }
    const validateSellerNote = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入备注'));
      }
      callback(this.valueLengthRule(value, '备注', 50));
    }
    return {
      categorys:[{}],
      categoryTopId:{},
      categorySeconds:[{}],
      categorySecondId:{},
      categorySecondDisabled: true,
      categoryThirds:[{}],
      categoryThirdId:[],
      categoryThirdDisabled: true,
      goods:[],
      imgList:[],
      imgThumb:[],
      /** 展示图的信息 **/
      imgUidThumb: [],
      /** 轮播图的信息 **/
      imgUidList: [],
      /** 上传的所有图片的信息 **/
      imgInfos: [],
      /** 库存信息 **/
      productInfos:{},
      /** 总库存 **/
      productAllNumber:0,
      productOfGoodsInfo:{},
      uploadHeaders: {
        'user-token':getToken()
      },
      attributeForm:{attributes: []},
      reviewStatusFilters:[
        {
          text:'待提交',
          value:15,
          type:'info'
        },
        {
          text:'审核中',
          value: 20,
          type:'warning'
        },
        {
          text:'驳回',
          value:30,
          type:'danger'
        },
        {
          text:'加库存',
          value: 50,
          type:'success'
        },
        {
          text:'待完成',
          value: 60,
          type:'success'
        }
      ],
      currentPage: 1,
      pagesize:20,
      goodsTotal:0,
      /** 列表界面 **/
      goodsListShow: true,
      /**编辑界面**/
      goodsEditShow: false,
      /** 库存 **/
      productInfoShow: false,
      /** 编辑界面商品基本信息 **/
      goodInfo:{},
      /** 编辑界面商品信息不可编辑 **/
      disabledGoods:true,
      /** 编辑详情页编辑按钮 **/
      editBooleanShow:false,
      /** 编辑详情页重置按钮 **/
      resetDisable:false,
      addInfoRules: {
        goodsName: [{required: true, trigger: 'blur', validator: validateGoodsName}],
        goodsUnit: [{required: true, trigger: 'blur', validator: validateGoodsUnit}],
        keywords: [{required: true, trigger: 'blur', validator: validateKeywords}],
        goodsWeight: [{required: true, trigger: 'blur', validator: validateGoodsWeight}],
        shopPrice: [{required: true, trigger: 'blur', validator: validateShopPrice}],
        costPrice: [{required: true, trigger: 'blur', validator: validateCostPrice}],
        marketPrice: [{required: true, trigger: 'blur', validator: validateMarketPrice}],
        goodsBrief: [{required: true, trigger: 'blur', validator: validateGoodsBrief}],
        goodsDesc: [{required: true, trigger: 'blur', validator: validateGoodsDesc}],
        sellerNote: [{required: true, trigger: 'blur', validator: validateSellerNote}],
      },
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData(){
      this.goods = [];
      this.goodsTotal = 0;
      let status = [15,20,30,50,60];
      forSaleApi.getGoodsDataList(null,status, this.currentPage, this.pagesize).then(res => {
        this.goods = res.data.records;
        this.goodsTotal = res.data.total;
      })
    },
    reviewStatusfilterTag(value, row){
      /** 状态列的筛选 需要filters filter-method属性**/
      return value === row.reviewStatus;
    },
    reviewStatusShowText(value){
      /** 拿到该行的值，然后遍历reviewStatusFilters拿到对应标签的名称 **/
      for (let i = 0; i < this.reviewStatusFilters.length; i++){
        if (value === this.reviewStatusFilters[i].value){
          return this.reviewStatusFilters[i].text;
        }
      }
      return value;
    },
    reviewStatusType(value){
      /** 拿到该行的值，然后遍历reviewStatusFilters拿到对应标签的样式 **/
      for (let i = 0; i < this.reviewStatusFilters.length; i++){
        if (value === this.reviewStatusFilters[i].value){
          return this.reviewStatusFilters[i].type;
        }
      }
      return "";
    },
    /** 分页---开始 **/
    handleSizeChange(val) {
      this.pagesize = val;
      this.initData();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initData();
      console.log(`当前页: ${val}`);
    },
    /** 分页---结束 **/
    /** 操作---开始 **/
    handleSubmit(index,row){
      /** 用户提交按钮 **/
      if (row.reviewStatus === 15 || row.reviewStatus === 30 || row.reviewStatus === 60){
        /** 待提交状态---开始 **/
        /** 提交提示 **/
        let content = (row.reviewStatus === 60)?'该操作将会提交商品等待上市，是否继续？':'该操作将会提交商品审核，是否继续？';
        this.$confirm(content, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          /** 确定提交 提交操作开始 **/
          let params = {
            id: row.id,
            reviewStatus: (row.reviewStatus === 60)?70:20
          }
          forSaleApi.updateGoods(params).then(res => {
            this.$notify.success({title:'成功', message:'提交成功！'});
            this.initData();
          }).catch(() => {
            this.$notify.error({title:'警告', message:'提交失败！'});
          })
          /** 提交操作结束 **/
        }).catch(() => {
          /** 取消提交 **/
          this.$notify.info({title:'提示', message:'已取消提交操作'});
        });
        /** 待提交状态---结束 **/
      } else {
        this.$notify.warning({title:'提示', message:'该状态不能提交！'});
      }
    },
    handleEdit(index,row){
      /** 编辑操作---开始 **/
      this.handlePageShow(2);
      /** 详情页编辑按钮，只有在待提交和驳回状态才显示 **/
      this.editBooleanShow = false;
      if (row.reviewStatus === 15 || row.reviewStatus === 30){
        this.editBooleanShow = true;
      }
      forSaleApi.getGoodsAllInfoById({id: row.id, catId: row.catId}).then(res => {
        /** 商品获取所有相关信息 **/
        /** 商品基本信息 **/
        this.goodInfo = res.data.goods;
        this.imgList = res.data.photoInfos.imgList;
        this.imgUidList = this.imgList;
        this.imgThumb = res.data.photoInfos.imgThumb;
        this.imgUidThumb = this.imgThumb;
        this.attributeForm.attributes = res.data.attributes.attributes;
        this.categorys = res.data.initCategorys.categorys;
        res.data.initCategorys.categorys.forEach((categorysTop, index) => {
          categorysTop.children.forEach((categorysSecond, index) => {
            if (categorysSecond.id === row.catId) {
              this.categoryTopId = categorysTop;
              this.categorySeconds = categorysTop.children;
              this.categorySecondId = categorysSecond;
              return true;
            } else {
              categorysSecond.children.forEach((categorysThird, index) => {
                if (categorysThird.id === row.catId) {
                  this.categoryTopId = categorysTop;
                  this.categorySeconds = categorysTop.children;
                  this.categorySecondId = categorysSecond;
                  this.categoryThirds = categorysSecond.children;
                  this.categoryThirdId = categorysThird;
                  return true;
                }
              });
            }
          });
        });
        /** 商品列表关闭 **/
        this.goodsListShow = false;
        /** 商品编辑页面显示 **/
        this.goodsEditShow = true;
      }).catch(() => {
        this.$notify.error({title:'警告', message:'信息查看失败'});
        this.blackGoodsList();
      })
    },
    stockEdit(index,row){
      /** 库存操作---开始 **/
      /** 商品信息初始化 **/
      this.productOfGoodsInfo = {};
      this.productOfGoodsInfo = {
        id: row.id,
        catId: row.catId,
        reviewStatus: 60
      };
      this.productAllNumber = 0;
      this.handlePageShow(5);
      forSaleApi.initProducts({id: row.id, catId: row.catId}).then(res => {
        this.productInfos = res.data;
        this.productAllNumber = res.data.productAllNumber;
      }).catch(() => {
        this.$notify.error({title:'警告', message:'商品库存信息获取失败'});
        /** 返回商品信息列表 **/
        this.handlePageShow(4)
      })
    },
    handleDelete(index,row){
      /** 删除操作---开始 **/
      this.$confirm('永久删除该商品信息， 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        forSaleApi.deleteGoodsById(row.id).then(res =>{
          /** 重新请求该页数据 **/
          this.initData();
          this.$notify.success({title:'成功', message:'商品删除成功！'});
          // this.goods.splice(index,1);
        }).catch(()=>{
          this.$notify.warning({title:'提示', message:'商品删除失败！'});
        })
      }).catch(() => {
        this.$notify.info({title:'提示', message:'已取消删除'});
      });
    },
    /** 操作---结束 **/
    /** 编辑页面---开始 **/
    blackGoodsList(){
      /** 返回商品信息列表 **/
      this.handlePageShow(4)
    },
    submitProducts(productsName){
      /** 库存信息提交 **/
      this.$refs[productsName].validate(valid => {
        if (valid) {
          this.productOfGoodsInfo.goodsNumber = this.productAllNumber;
          let params = {
            products: JSON.parse(JSON.stringify(this.productInfos.products)),
            goodsInfo: JSON.parse(JSON.stringify(this.productOfGoodsInfo)),
          }
          forSaleApi.saveProductsInfos(params).then(res => {
            this.$notify.success({title:'成功', message:'提交成功！'});
            /** 提交成功后返回列表页 **/
            this.handlePageShow(4)
          }).catch(() => {
            this.$notify.error({title:'警告', message:'提交失败！'});
            return false;
          });
        } else {
          /** 基本信息不合规 **/
          this.$notify.info({title:'提示', message:'信息不合规！'});
          return false
        }
      });
    },
    resetAllInfo(){
      /** 信息重置 **/
      this.handleEdit(null, {id: this.goodInfo.id, catId: this.goodInfo.catId});
      this.editBoolean();
    },
    // rejectBoolean(){
    //   /** 驳回按钮 **/
    //   this.$confirm('是否继续驳回该商品信息?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     let params = {
    //       id: this.goodInfo.id,
    //       reviewStatus: 30
    //     }
    //     forSaleApi.updateGoods(params).then(res =>{
    //       /** 重新请求该页数据 **/
    //       this.$message.success("商品驳回成功")
    //       /** 数据重新加载 **/
    //       this.handleEdit(null, {id: this.goodInfo.id, catId: this.goodInfo.catId});
    //     }).catch(()=>{
    //       this.$message.warning("商品驳回失败！")
    //       return false;
    //     })
    //   }).catch(() => {
    //     this.$message({
    //       type: 'info',
    //       message: '已取消驳回'
    //     });
    //   });
    // },
    editBoolean(){
      /** 详情页面编辑按钮 **/
      /** 编辑详情页可编辑 **/
      this.disabledGoods = false;
      this.categorySecondDisabled = false;
      this.categoryThirdDisabled = false;
      /** 编辑详情页重置按钮显示 **/
      this.resetDisable = true;
    },
    changeTopCategory(value){
      /** Top分类change事件 **/
      this.categoryThirdId = ""
      this.categoryThirds = [];
      this.categoryThirdDisabled = true;
      this.categorySecondId = ""
      this.categorySeconds = [];
      this.categorySecondDisabled = true;
      /** 重新显示属性列 **/
      this.attributeForm = {attributes: []};
    },
    changeTopCategory(value){
      /** Top分类change事件 **/
      this.categoryThirdId = ""
      this.categoryThirds = [];
      this.categoryThirdDisabled = true;
      this.categorySecondId = ""
      this.categorySeconds = [];
      this.categorySecondDisabled = true;
      /** 重新显示属性列 **/
      this.attributeForm = {attributes: []};
      if (value.hasOwnProperty("children")&&value.children.length > 0){
        /** 该Top分类下有子分类 放开可选择 **/
        this.categorySeconds = value.children;
        this.categorySecondDisabled = false;
      }
    },
    changeSecondCategory(value){
      /** 二级分类change事件 **/
      this.categoryThirdId = ""
      this.categoryThirds = [];
      this.categoryThirdDisabled = true;
      /** 重新显示属性列 **/
      this.attributeForm = {attributes: []};
      if (value.hasOwnProperty("children")&&value.children.length > 0){
        /** 该Top分类下有子分类 放开可选择 **/
        this.categoryThirds = value.children;
        this.categoryThirdDisabled = false;
      }
      if (value.id.length == 32){
        this.initAttribute(value.id)
      }
    },
    changeThirdCategory(value){
      /** 三级分类change事件 **/
      /** 重新显示属性列 **/
      this.attributeForm = {attributes: []};
      if (value.hasOwnProperty("id")&&value.id.length == 32){
        this.initAttribute(value.id)
      }
    },
    initAttribute(value){
      /** 选择分类后，初始化分类属性 **/
      forSaleApi.getAttributes(value).then(res => {
        for (let i = 0; i < res.data.length; i++){
          /** attributes表没有shopAttr的attrSort字段 **/
          res.data[i].attrSort =  res.data[i].sortOrder;
          this.attributeForm.attributes.push({goodsAttrs: new Array(JSON.parse(JSON.stringify(res.data[i])))})
        }
        // this.attributeForm.attributes = JSON.parse(JSON.stringify(res.data));
      }).catch(() => {

      })
    },
    removeGoodsAttr(goodsAttr, attribute){
      /** 移除分类属性列 **/
      if(attribute.goodsAttrs.length < 2){
        /** 如果该属性列只剩一列了，就不能删除了 **/
        this.$notify.warning({title:'提示', message:'该属性只剩最后一列，不能再删除了！'});
        return false;
      }
      let index = attribute.goodsAttrs.indexOf(goodsAttr);
      if (index !== -1){
        attribute.goodsAttrs.splice(index, 1);
      }
    },
    addGoodsAttr(attribute, indexTop){
      /** 添加分类属性值 **/
      let maxObj = attribute.goodsAttrs[attribute.goodsAttrs.length-1];
      attribute.goodsAttrs.push({attrId:maxObj.attrId, attrName:maxObj.attrName, attrSort:maxObj.attrSort+5});
    },
    restGoodsAttr(attribute, indexTop){
      this.$refs['attribute'][indexTop].resetFields();
    },
    exceedImgList(file, fileList){
      this.$notify.warning({title:'提示', message:'当前限制选择10个文件，已超出了可选择数量'});
    },
    beforeUploadImgList(file){
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      this.beforeUploadImgRule(isJPG,"JPG",isLt2M,"2MB")
      return isJPG && isLt2M;
    },
    successImgList(response, file, fileList){
      this.imgUidList = fileList;
    },
    removeImgList(file, fileList){
      this.imgUidList = fileList;
    },
    exceedImgThumb(file, fileList){
      /** 展示图超出数量限制的钩子 **/
      this.$notify.warning({title:'提示', message:'当前限制选择15个文件，已超出了可选择数量'});
    },
    beforeUploadImgThumb(file) {
      /** 展示图上传前的钩子 **/
      const isJPG = file.type === 'image/jpeg';
      const isLt1M = file.size / 1024 / 1024 < 2;
      this.beforeUploadImgRule(isJPG,"JPG",isLt1M,"2MB")
      return isJPG && isLt1M;
    },
    successImgThumb(response, file, fileList){
      /** 展示图成功后的钩子 **/
      this.imgUidThumb = fileList;
    },
    removeImgThumb(file, fileList){
      /** 文件列表移除时，移除后的钩子 **/
      this.imgUidThumb = fileList;
    },
    beforeUploadImgRule(isFormat,formatValue, isLt, ltValue){
      // 图片格式、大小规则检验
      if (!isFormat) {
        this.$notify.warning({title:'提示', message:'上传图片只能是 '+formatValue+' 格式!'});
      }
      if (!isLt) {
        this.$notify.warning({title:'提示', message:'上传图片大小不能超过 '+ltValue+'!'});
      }
    },
    submitForm(goodInfo){
      /** 编辑/详情页提交 **/
      /** 商品是否分类 **/
      if (!this.categorySecondId.hasOwnProperty("id") || this.categorySecondId.id.length != 32){
        /** 商品没有二级或三级分类，只要没有二级分类就没有三级分类，而二级分类有了，分类选项目的也达到了 **/
        this.$notify.warning({title:'提示', message:'商品必须选择二级或三级分类'});
        return false;
      }
      /** 商品分类属性列检测 **/
      this.attributeForm.attributes.forEach((attribute, index) => {
        this.$refs['attribute'][index].validate(valid => {
          if (!valid){
            this.$notify.warning({title:'提示', message:'商品分类属性值不合规'});
            return false;
          }
        })
      });
      if (this.imgUidList.length < 1){
        this.$notify.warning({title:'提示', message:'详情轮播图不能为空！'});
        return false;
      }
      if (this.imgUidThumb.length < 1){
        this.$notify.warning({title:'提示', message:'展示图不能为空！'});
        return false;
      }
      this.imgInfos = [];
      this.imgUidList.forEach((imgList, index) => {
        /** 获取详情轮播图的信息 **/
        this.imgInfos.push({
          url: imgList.hasOwnProperty("photoSort")?imgList.url:imgList.response.data[imgList.name],
          type:2,
          photoSort: (index + 1) * 10
        });
      });
      this.imgUidThumb.forEach((imgList, index) => {
        /** 获取展示图的信息 **/
        this.imgInfos.push({
          url: imgList.hasOwnProperty("photoSort")?imgList.url:imgList.response.data[imgList.name],
          type:1,
          photoSort: (index + 1) * 10
        });
      });
      /** 定义商品属性值信息 **/
      let goodsAttrInfos = JSON.parse(JSON.stringify(this.attributeForm.attributes));
      this.goodInfo.catId = (!this.categoryThirdId.hasOwnProperty("id") || this.categoryThirdId.id.length != 32)==true?this.categorySecondId.id:this.categoryThirdId.id;
      this.$refs[goodInfo].validate(valid => {
        if (valid) {
          forSaleApi.updateGoodsAllInfo(JSON.parse(JSON.stringify(this.goodInfo)),this.imgInfos,goodsAttrInfos).then(res => {
            /** 商品跟新所有数据 **/
            this.$notify.success({title:'成功', message:'商品信息更新成功'});
            this.handlePageShow(3);
            return true;
          }).catch(() => {
            this.$notify.error({title:'警告', message:'商品信息更新失败！'});
            return false;
          });
        } else {
          /** 基本信息不合规 **/
          this.$notify.warning({title:'提示', message:'信息不合规！'});
          return false
        }
      })
    },
    valueLengthRule(value, name, maxlength){
      if (value.length > maxlength){
        return new Error(name + '不能超过'+ maxlength +'个字')
      }
    },
    productNumberRule(rule, value, callback){
      /** 库存数据规则校验 **/
      if (value === '') {
        callback(new Error('请输库存数据'));
      }
      if(!(/^(?:[0-9]{1,7}|100000)$/.test(value))){
        callback(new Error('范围（1~10000000）'));
      }
      callback();
    },
    productWarnNumberRule(rule, value, callback){
      /** 库存警报数据规则校验 **/
      if (value === '') {
        callback(new Error('请输库存警报数据'));
      }
      if(!(/^(?:[0-9]{1,7}|100000)$/.test(value))){
        callback(new Error('范围（1~10000000）'));
      }
      callback();
    },
    productPriceRule(rule, value, callback){
      /** 商品尺寸溢价 **/
      if (value === ''){
        callback("请输入商品该尺寸溢价");
      } else {
        let marketPriceRegex = /^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$/
        if (!marketPriceRegex.test(value)){
          callback(new Error('范围（0.00~9999999.99）'));
        }
      }
      callback();
    },
    productNumberChange(value){
      /** 总库存实时跟新 **/
      this.productAllNumber = 0;
      this.productInfos.products.forEach((product, index) => {
        if((/^(?:[0-9]{1,7}|100000)$/.test(product.productNumber))){
          this.productAllNumber = parseInt(this.productAllNumber)+parseInt(product.productNumber);
        }
      });
    },
    /** 编辑页面---结束 **/

    handlePageShow(type){
      /** 操作按钮事件对应页面显示 **/
      switch (type) {
        case 1:
          /** 列表页提交按钮 **/
        break;
        case 2:
          /** 列表页编辑/详情按钮
           * 列表的关闭和详情页显示放在了拿到数据的后面
           **/
          /** 编辑详情页不可编辑 **/
          this.disabledGoods = true;
          this.categorySecondDisabled = true;
          this.categoryThirdDisabled = true;
          /** 编辑详情页重置/提交按钮关闭 **/
          this.resetDisable = false;
          /** 信息初始化---开始 **/
          this.goodInfo = {};
          this.imgList =[];
          this.imgThumb = [];
          /** 重置展示图的信息 **/
          this.imgUidThumb = [];
          /** 重置轮播图的信息 **/
          this.imgUidList = [];
          /** 重置上传的所有图片的信息 **/
          this.imgInfos = [];
          /** 分类信息初始化--开始**/
          this.categorys = [{}]
          this.categoryTopId = {};
          this.categorySeconds = [{}];
          this.categorySecondId = {};
          this.categorySecondDisabled =  true;
          this.categoryThirds = [{}];
          this.categoryThirdId = {};
          this.categoryThirdDisabled = true;
          this.attributeForm.attributes=[];
          /** 分类信息初始化---结束**/
        break;
        case 3:
          /** 编辑/详情页跟新成功 **/
          /** 编辑详情页不可编辑 **/
          this.disabledGoods = true;
          /** 二级分类不可选 **/
          this.categorySecondDisabled = true;
          /** 三级级分类不可选 **/
          this.categoryThirdDisabled = true;
          /** 编辑详情页重置/提交按钮关闭 **/
          this.resetDisable = false;
        break;
        case 4:
          /** 编辑/详情、库存页返回 **/
          /** 重新请求该页数据 **/
          this.initData();
          /** 商品列表显示 **/
          this.goodsListShow = true;
          /** 商品编辑页面关闭 **/
          this.goodsEditShow = false;
          /** 商品库存页关闭 **/
          this.productInfoShow = false;
        break;
        case 5:;
          /** 库存按钮 **/
          /** 初始化库存信息 **/
          this.productInfos = {};
          /** 商品列表关闭 **/
          this.goodsListShow = false;
          /** 商品库存页显示 **/
          this.productInfoShow = true
        break;
        default:break;
      }
    },
    buttonDisabled(reviewStatus, type){
      /** 操作按钮---状态显示 **/
      let disableValue = true;
      switch (type) {
        case 1:
          switch (reviewStatus) {
            /** 提交 **/
            case 15:disableValue = false;break;//待提交
            case 20:disableValue = true;break;//审核中
            case 30:disableValue = false;break;//驳回
            case 50:disableValue = true;break;//加库存
            case 60:disableValue = false;break;//待完成
            default:disableValue = false;
          }
        break;
        case 2:
          switch (reviewStatus) {
            /** 编辑 **/
            case 15:disableValue = false;break;//待提交
            case 20:disableValue = false;break;//审核中
            case 30:disableValue = false;break;//驳回
            case 50:disableValue = false;break;//加库存
            case 60:disableValue = false;break;//待完成
            default:disableValue = true;
          }
        break;
        case 3:
          switch (reviewStatus) {
            /** 库存 **/
            case 15:disableValue = true;break;//待提交
            case 20:disableValue = true;break;//审核中
            case 30:disableValue = true;break;//驳回
            case 50:disableValue = false;break;//加库存
            case 60:disableValue = false;break;//待完成
            default:disableValue = true;
          }

          break;
        case 4:
          switch (reviewStatus) {
            /** 删除 **/
            case 15:disableValue = false;break;//待提交
            case 20:disableValue = true;break;//审核中
            case 30:disableValue = false;break;//驳回
            case 50:disableValue = true;break;//加库存
            case 60:disableValue = true;break;//待完成
            default:disableValue = true;
          }
          break;
        default:
          disableValue = true;
      }
      return disableValue;
    }
  }
}
</script>

